package com.ibpd.shopping.web.controller.manage;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.h2.util.StringUtils;
import org.jsoup.helper.StringUtil;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.ibpd.dao.impl.HqlParameter;
import com.ibpd.henuocms.common.IbpdLogger;
import com.ibpd.henuocms.entity.NodeEntity;
import com.ibpd.henuocms.entity.ext.TreeNodeEntity;
import com.ibpd.henuocms.entity.ext.TreeNodeUtil;
import com.ibpd.henuocms.web.controller.manage.BaseController;
import com.ibpd.shopping.entity.CatalogEntity;
import com.ibpd.shopping.entity.MallHomePageEntity;
import com.ibpd.shopping.entity.ProductEntity;
import com.ibpd.shopping.service.MallHomePage.IMallHomePageService;
import com.ibpd.shopping.service.MallHomePage.MallHomePageServiceImpl;
import com.ibpd.shopping.service.catalog.CatalogServiceImpl;
import com.ibpd.shopping.service.catalog.ICatalogService;
import com.ibpd.shopping.service.product.IProductService;
import com.ibpd.shopping.service.product.ProductServiceImpl;

@Controller
public class MallHomePage extends BaseController {
	@RequestMapping("Manage/MallHomePage/index.do")
	public String index(Model model,HttpServletRequest req,String type) throws IOException{
		model.addAttribute("pageTitle","APP商城首页管理");
		model.addAttribute("type",type);
		
		return "manage/s_mall/index";
	}
	@RequestMapping("Manage/MallHomePage/list.do")
	public void list(HttpServletResponse resp,String type,HttpServletRequest req) throws IOException{
		IMallHomePageService mallServ=(IMallHomePageService) getService(MallHomePageServiceImpl.class);
		String query="";
		Integer tp=0;
		if(type!=null){
			if(type.trim().toLowerCase().equals("pop")){
				tp=MallHomePageEntity.TYPE_幻灯;
			}else if(type.trim().toLowerCase().equals("jrtj")){
				tp=MallHomePageEntity.TYPE_今日推荐;
			}else if(type.trim().toLowerCase().equals("hyzm")){
				tp=MallHomePageEntity.TYPE_会员专卖;
			}else if(type.trim().toLowerCase().equals("rmsc")){
				tp=MallHomePageEntity.TYPE_热门市场;
			}else{
				tp=-1;
			}
		}
//		mallServ.getDao().clearCache();
		super.getList(req, mallServ, resp, "desc", 0, 100, "order", " type="+tp);
	}
	@RequestMapping("Manage/MallHomePage/prodTree.do")
	public void prodTree(HttpServletResponse resp,HttpServletRequest req,Long id) throws IOException{
//		"id":12,
//		"text":"Washington",
//		"state":"closed",
//		children
		id=id==null?0:id;
		id=id<=0?0:id;
		ICatalogService cataServ=(ICatalogService) getService(CatalogServiceImpl.class);
		if(id!=0){
			CatalogEntity ce=cataServ.getEntityById(id);
			if(ce!=null){
				if(ce.getLeaf()){
					List<HqlParameter> pList=new ArrayList<HqlParameter>();
					pList.add(new HqlParameter("pid",id,null));
					List<CatalogEntity> cataList=cataServ.getList("from "+cataServ.getTableName()+" where pid=:pid",pList,"order asc",-1,-1);
					List<NodeEntity> nodeList=convertToNodeList(cataList);
					List<TreeNodeEntity> treeNodeList=TreeNodeUtil.converToTreeNode(nodeList);
					JSONArray jsonArray = JSONArray.fromObject( treeNodeList );
					String rtnJson=jsonArray.toString();
					super.printJsonData(resp, rtnJson);				
				}else{
					IProductService  prodServ=(IProductService) getService(ProductServiceImpl.class);
					List<ProductEntity> prodList=prodServ.getListByCatalogId(id, 100, 0, "", "id desc");
					List<TreeNodeEntity> treeNodeList=TreeNodeUtil.converToTreeNode(prodList);
					JSONArray jsonArray = JSONArray.fromObject( treeNodeList );
					String rtnJson=jsonArray.toString();
					super.printJsonData(resp, rtnJson);
				}
			}			
		}else{
			List<HqlParameter> pList=new ArrayList<HqlParameter>();
			pList.add(new HqlParameter("pid",id,null));
			List<CatalogEntity> cataList=cataServ.getList("from "+cataServ.getTableName()+" where pid=:pid",pList,"order asc",-1,-1);
			List<NodeEntity> nodeList=convertToNodeList(cataList);
			List<TreeNodeEntity> treeNodeList=TreeNodeUtil.converToTreeNode(nodeList);
			JSONArray jsonArray = JSONArray.fromObject( treeNodeList );
			String rtnJson=jsonArray.toString();
			super.printJsonData(resp, rtnJson);							
		}
	}
	private List<NodeEntity> convertToNodeList(List<CatalogEntity> cataList){
		if(cataList==null)return null;
		List<NodeEntity> nodeList=new ArrayList<NodeEntity>();
		for(CatalogEntity c:cataList){
			NodeEntity ne=new NodeEntity();
			ne.setId(c.getId());
			ne.setLeaf(true);
			ne.setParentId(c.getPid());
			ne.setText(c.getName());
			nodeList.add(ne);
		}
		return nodeList;
	}
	@RequestMapping("Manage/MallHomePage/props.do")
	public String props(Long id,String type,Model model) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id==null || id<0L){
			model.addAttribute("errorMsg","参数错误");
			return super.ERROR_PAGE;
		}
		type=type==null?"":type;
		IMallHomePageService mallServ=(IMallHomePageService) getService(MallHomePageServiceImpl.class);
		MallHomePageEntity ce=mallServ.getEntityById(id);
		if(ce==null){
			model.addAttribute("errorMsg","没有找到");
			return super.ERROR_PAGE;
		}
		model.addAttribute("type",type);
		model.addAttribute("pageTitle","参数设置");
		model.addAttribute("htmls",super.getHtmlString(ce, "mall.edit.field"));
		model.addAttribute("entity",ce);
		return "manage/s_mall/props";
	}	
	@RequestMapping("Manage/MallHomePage/saveProp.do")
	public void saveProps(Long id,String field,String value,HttpServletResponse resp) throws NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, IOException{
		if(id!=null && id!=-1){
			IMallHomePageService mallServ=(IMallHomePageService) getService(MallHomePageServiceImpl.class);
			MallHomePageEntity cata=mallServ.getEntityById(id);
				if(cata!=null){
					//先确定参数类型
					Method tmpMethod=cata.getClass().getMethod("get"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{});
					
					
					Method method=cata.getClass().getMethod("set"+field.substring(0,1).toUpperCase()+field.substring(1), new Class[]{tmpMethod.getReturnType()});
					Object val=getValue(value,tmpMethod.getReturnType().getSimpleName());
					IbpdLogger.getLogger(this.getClass()).info("value="+val);
					method.invoke(cata, val);
					mallServ.saveEntity(cata);
//					mallServ.getDao().clearCache();
					super.printMsg(resp, "99", cata.getId().toString(), "保存成功");		
				}else{
					super.printMsg(resp, "-1", "", "没有该类别");
				}
		}else{
			super.printMsg(resp, "-2", "", "参数错误");			
		}
	}
	@RequestMapping("Manage/MallHomePage/toAdd.do")
	public String toAdd(Model model,String type,HttpServletResponse resp) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{

		model.addAttribute("pageTitle","添加");
		if(type==null){
			model.addAttribute("msg","参数错误");
			return ERROR_PAGE;
		}
		model.addAttribute("type",type);
		model.addAttribute("htmls",super.getHtmlString(null, "mall.add.field"));
		return "manage/s_mall/add";
	}
	@RequestMapping("Manage/MallHomePage/toEdit.do")
	public String toEdit(Long id,String type,Model model,HttpServletResponse resp) throws IOException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(id==null){
			return this.ERROR_PAGE;
		}
		IMallHomePageService mallServ=(IMallHomePageService) getService(MallHomePageServiceImpl.class);
		MallHomePageEntity cata=mallServ.getEntityById(id);
		//model.addAttribute("type",getIntType(type));
		if(cata==null){
			model.addAttribute("errorMsg","没有该类别");
			return this.ERROR_PAGE;
		}
		model.addAttribute("pageTitle","编辑");
		if(type==null){
			model.addAttribute("msg","参数错误");
			return ERROR_PAGE;
		}
		model.addAttribute("type",type);
		model.addAttribute("htmls",super.getHtmlString(cata, "mall.edit.field"));
		model.addAttribute("entity",cata);
		return "manage/s_mall/edit";
	}
	@RequestMapping("Manage/MallHomePage/doEdit.do")
	public void doEdit(MallHomePageEntity entity,HttpServletResponse resp) throws IOException, NoSuchMethodException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
		if(entity!=null && entity.getId()!=null && entity.getId()!=-1L){
			
			IMallHomePageService mallServ=(IMallHomePageService) getService(MallHomePageServiceImpl.class);
			MallHomePageEntity cata=mallServ.getEntityById(entity.getId());
			if(cata==null){
				super.printMsg(resp, "-1", "", "没有找到");
				return;
			}else{
				Integer tp=cata.getType();
				swap(entity,cata);
				cata.setType(tp);
				mallServ.saveEntity(cata);
				super.printMsg(resp, "99", cata.getId().toString(), "保存成功");
				return;
			}
		}else{
			super.printMsg(resp, "-2", "", "参数错误");
			return;
		}
		
	}
	@RequestMapping("Manage/MallHomePage/doAdd.do")
	public void doAdd(MallHomePageEntity entity,HttpServletResponse resp,String _type) throws IOException{
		
		IMallHomePageService mallServ=(IMallHomePageService) getService(MallHomePageServiceImpl.class);
		_type=_type==null?"0":_type;
		if(StringUtils.isNumber(_type))
			entity.setType(Integer.valueOf(_type));
		mallServ.saveEntity(entity);	
		super.printMsg(resp, "99", "-1", "保存成功");
		 
	}
	@RequestMapping("Manage/MallHomePage/doDel.do")
	public void doDel(String ids,HttpServletResponse resp) throws IOException{
		if(StringUtil.isBlank(ids)){
			super.printMsg(resp, "-1", "", "没有选择项");	
		}
		IMallHomePageService mallServ=(IMallHomePageService) getService(MallHomePageServiceImpl.class);
		mallServ.batchDel(ids);
		super.printMsg(resp, "99", "", "操作成功");	
	}
}